package com.transaction.demo.consumer.mq;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

import com.google.gson.reflect.TypeToken;
import com.transaction.demo.accounting.AccountingVoucherService;
import com.transaction.demo.accounting.vo.req.AccountingVoucherAddReqVo;
import com.transaction.demo.accounting.vo.req.AccountingVoucherReqVo;
import com.transaction.demo.accounting.vo.resp.AccountingVoucherRespVo;
import com.transaction.demo.common.util.JsonUtils;
import com.transaction.demo.message.MessageService;

@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = "accounting_notify", topic = "ACCOUNTING_NOTIFY")
public class AccountingMessageListener implements RocketMQListener<String> {

	@Autowired(required = false)
	private AccountingVoucherService accountingVoucherService;

	@Autowired(required = false)
	private MessageService messageService;

	@Override
	public void onMessage(String s) {
		log.info("接收到会计凭证消息：{}", s);

		Map<String, String> params = JsonUtils.fromJson(s, new TypeToken<Map<String, String>>() {
		}.getType());

		//保存凭证
		AccountingVoucherAddReqVo voucherAddReqVo = new AccountingVoucherAddReqVo();
		voucherAddReqVo.setCreateTime(new Date());
		voucherAddReqVo.setEditTime(new Date());
		voucherAddReqVo.setEntryType((short) 0);
		voucherAddReqVo.setRequestNo("12");
		voucherAddReqVo.setFromSystem((short) 0);
		voucherAddReqVo.setVoucherNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
		voucherAddReqVo.setAccountingDate(new Date());
		voucherAddReqVo.setBankChangeAmount("1");
		voucherAddReqVo.setPayerAccountNo("1");
		voucherAddReqVo.setReceiverAccountNo("1");
		voucherAddReqVo.setBankAccount("1");
		voucherAddReqVo.setBankChannelCode("1");
		voucherAddReqVo.setPayerChangeAmount("1");
		voucherAddReqVo.setReceiverChangeAmount("1");
		voucherAddReqVo.setProfit("1");
		voucherAddReqVo.setIncome("1");
		voucherAddReqVo.setCost("1");
		voucherAddReqVo.setRemark("test");
		assert params != null;
		voucherAddReqVo.setBankOrderNo(params.get("businessId"));
		voucherAddReqVo.setPayerAccountType((short) 0);
		voucherAddReqVo.setPayAmount("10000");
		voucherAddReqVo.setReceiverAccountType((short) 0);
		voucherAddReqVo.setReceiverFee("1");
		voucherAddReqVo.setPayerFee("1");

		accountingVoucherService.saveAccountingVoucher(voucherAddReqVo);

		//删除消息
		messageService.deleteMessageByMessageId(params.get("messageId"));
	}
}
